package org.example.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.config.PageBean;
import org.example.config.Result;
import org.example.domain.CarDictType;
import org.example.listener.CarDictTypeListener;
import org.example.service.CarDictTpeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("carDictType")
public class CarDictTypeController {

    @Autowired
    private CarDictTpeService carDictTpeService;

    @RequestMapping("list")
    public Result list(CarDictType carDictType, PageBean bean){

        PageHelper.startPage(bean);
        List<CarDictType> list = carDictTpeService.list(carDictType);
        PageInfo<CarDictType> info = new PageInfo<>(list);
        return Result.success(info);
    }

    @RequestMapping("add")
    public Result add(CarDictType carDictType){
        carDictType.setCreateTime(new Date());
        return Result.success(carDictTpeService.add(carDictType));
    }

    @RequestMapping("update")
    public Result update(CarDictType carDictType){

        return Result.success(carDictTpeService.update(carDictType));
    }

    @RequestMapping("delete")
    public Result delete(Integer dictId){

        return Result.success(carDictTpeService.delete(dictId));
    }



    @RequestMapping("download")
    public void download(HttpServletResponse response) throws IOException {

        List<CarDictType> list = carDictTpeService.listAll();
        String fileName=CarDictType.class.getName();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CarDictType.class).sheet("字典数据").doWrite(list);
    }

    @RequestMapping("upload")
    public Map<String,Object> upload(MultipartFile file){

        HashMap<String, Object> map = new HashMap<>();

        try {
            map.put("code",200);
            EasyExcel.read(file.getInputStream(),CarDictType.class,new CarDictTypeListener(carDictTpeService)).sheet().doRead();
        }catch (IOException e){
            map.put("code",500);
            e.printStackTrace();
        }
        return map;
    }


}
